﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using com.ubosi.model.Entity;
using com.ubosi.model.Spider;
using com.ubosi.spider.hotel;
using com.ubosi.spider.core.Net;
using com.ubosi.spider.config;
using com.ubosi.common;

namespace com.ubosi.spider.app.Hotel
{
    public partial class SpiderHotel : Form
    {
        public SpiderHotel()
        {
            InitializeComponent();
        }

        public void Begin()
        {
            UBOSIEntities dataContext = new UBOSIEntities();
            var query = from city in dataContext.City 
                        select city;

            NetSpider netSpider = new NetSpider(SpiderGlobal.RequestSetting, null);
            int cityCount = 0;
            int hotelCount = 0;
            foreach (var city in query)
            {                
                List<HotelBaseInfo> list = new SpiderElongHotelInfo().GetHotelListInfo(city.CityId, netSpider);
                Save(list,city.CityId);
                cityCount++;
                hotelCount += list.Count;
            }
            MessageBox.Show(string.Format("城市：{0}个；酒店{1}个", cityCount, hotelCount));
        }

        private void Save(List<HotelBaseInfo> list,string cityid)
        {
            UBOSIEntities dataContext = new UBOSIEntities();

            foreach(HotelBaseInfo hbi in list)
            {
                com.ubosi.model.Entity.Hotel hotel = new com.ubosi.model.Entity.Hotel();
                hotel.CityId = cityid;
                hotel.HotelId =  hbi.HotelID;
                hotel.HotelName = hbi.HotelCnName;
                hotel.HotelNameEn = hbi.HotelEnName;
                hotel.UpdateTime = DateTime.Now;
                dataContext.AddToHotel(hotel);

                HotelMap hotelMap = new HotelMap();
                hotelMap.HotelId = hotel.HotelId;
                hotelMap.SrcId = "elong";
                hotelMap.SrcHotelId = hbi.HotelID;
                dataContext.AddToHotelMap(hotelMap);                
            }
            dataContext.SaveChanges();
            
        }
        
        private void CreateConfig()
        {
            SpiderConfig spiderConfig = new SpiderConfig();
            SpiderHotelInfoConfig spiderHotelInfoConfig = new SpiderHotelInfoConfig();
            spiderHotelInfoConfig.SourceId = "elong";
            spiderHotelInfoConfig.SpiderUrl = "http://www.elong.com/hotels/details.aspx?m=detail&hotelid={0}";
            spiderHotelInfoConfig.HotelNameRegx = "<title>([\\w\\W]+?)</title>";
            spiderHotelInfoConfig.HotelAddressRegx = "<span style=\"font-family: '宋体';\">([\\w\\W]+?)&nbsp;";
            spiderHotelInfoConfig.SnowntownNameRegx = "<a href=\"search.aspx?areaid=([\\w\\W]+?)&cityid=([\\w\\W]+?)\">([\\w\\W]+?)</a>";
            spiderHotelInfoConfig.HotelStarRegx = "<input type=\"hidden\" name=\"Star\" id=\"Star\" value=\"([\\w\\W]+?)\" />";
            spiderHotelInfoConfig.HotelLatRegx = "<input type=\"hidden\" name=\"Latitude\" id=\"Latitude\" value=\"([\\w\\W]+?)\" />";
            spiderHotelInfoConfig.HotelLngRegx = "<input type=\"hidden\" name=\"Longitude\" id=\"Longitude\" value=\"([\\w\\W]+?)\" />";
            spiderHotelInfoConfig.HotelTrafficRegx = "<span style=\"font-family: '宋体';\">交通：</span>([\\w\\W]+?)</span>";
            spiderHotelInfoConfig.PromotionRegx = "<div class=\"cp_txtwc cp_hd\" style=\"padding:3px 8px 0 0;\">([\\w\\W]+?)</div>";
            spiderHotelInfoConfig.HotelIntroRegx = "<div class=\"txs_dec\">([\\w\\W]+?)</div>";
            spiderHotelInfoConfig.ServicesRegx = "<tr><th>酒店服务</th><td><span>([\\w\\W]+?)</span>";
            spiderHotelInfoConfig.FacilitiesRegx = "<tr><th>房间设施</th><td><span>([\\w\\W]+?)</span>";
            spiderHotelInfoConfig.FoodRegx = "<tr><th>餐饮设施</th><td><span>([\\w\\W]+?)</span>";
            spiderHotelInfoConfig.EntertainmentRegx = "<tr><th>康体娱乐</th><td><span>([\\w\\W]+?)</span>";
            spiderHotelInfoConfig.MeetingRegx = "<tr><th>会议设施</th><td><span>([\\w\\W]+?)</span>";
            spiderConfig.HotelInfo = new List<SpiderHotelInfoConfig>();
            spiderConfig.HotelInfo.Add(spiderHotelInfoConfig);
            SerializerUtility.SerializeToFile(spiderConfig,Environment.CurrentDirectory+"\\Config\\SpiderConfig.xml");
        }

        private com.ubosi.model.Entity.Hotel SpiderHotelInfo(string hotelid)
        {
            com.ubosi.model.Entity.Hotel hotel = new com.ubosi.model.Entity.Hotel();
            NetSpider netSpider = new NetSpider(SpiderGlobal.RequestSetting, null);
            SpiderConfig sc = (SpiderConfig)SerializerUtility.DeSerializeFromFile(typeof(SpiderConfig), Environment.CurrentDirectory + "\\Config\\SpiderConfig.xml");
            com.ubosi.spider.hotel.HoteInfo.SpiderElongHotelInfo spiderElongHotelInfo = new com.ubosi.spider.hotel.HoteInfo.SpiderElongHotelInfo(netSpider, sc.HotelInfo[0]);
            hotel = spiderElongHotelInfo.GetHotelInfo(hotelid);
            return hotel;
            
        }

        private void InitHotelInfo(string CityId)
        {
            UBOSIEntities dataContext = new UBOSIEntities();
            var query = from hotel in dataContext.Hotel
                        where hotel.CityId==CityId && hotel.Status==0
                        select hotel;
                       
            int hotelCount = 0;
            foreach (var hotel in query)
            {
                try
                {
                    com.ubosi.model.Entity.Hotel spiderHotel = SpiderHotelInfo(hotel.HotelId);
                    if (Update(hotel.HotelId,spiderHotel))
                        hotelCount++;
                    Random r = new Random();
                    int i = r.Next(1,5);
                    i = i == 0 ? 1 : i;

                    System.Threading.Thread.Sleep(i * 1000);
                }
                catch(Exception ex)
                {
                }                
            }        
            if (hotelCount>0)
                MessageBox.Show("更新了" + hotelCount.ToString() + "个酒店");
        }

        private bool Update(string hotelid, com.ubosi.model.Entity.Hotel spiderHotel)
        {
            if (spiderHotel == null)
                return false;
            try
            {
                UBOSIEntities dataContext = new UBOSIEntities();
                var query = from hotel in dataContext.Hotel
                            where hotel.HotelId == hotelid
                            select hotel;
                com.ubosi.model.Entity.Hotel updateHotel = query.ToList()[0];

                updateHotel.HotelStar = spiderHotel.HotelStar;
                updateHotel.HotelAddress = spiderHotel.HotelAddress;
                updateHotel.HotelIntro = spiderHotel.HotelIntro;
                updateHotel.Lat = spiderHotel.Lat;
                updateHotel.Lng = spiderHotel.Lng;
                updateHotel.Services = spiderHotel.Services;
                updateHotel.HotelTraffic = spiderHotel.HotelTraffic;
                updateHotel.Meeting = spiderHotel.Meeting;
                updateHotel.Entertainment = spiderHotel.Entertainment;
                updateHotel.Facilities = spiderHotel.Facilities;
                updateHotel.Food = spiderHotel.Food;
                updateHotel.Promotion = spiderHotel.Promotion;
                if (string.IsNullOrEmpty(updateHotel.SnowntownId))
                {
                    int id = GetSnowntownId(spiderHotel.SnowntownId);
                    if (id > 0)
                        updateHotel.SnowntownId = id.ToString();
                }
                updateHotel.Status = 1;
                updateHotel.UpdateTime = DateTime.Now;

                if (!string.IsNullOrEmpty(spiderHotel.HotelPic))
                {
                    string fileName = ImageSpider.Download(hotelid + ".jpg", @"C:\工作目录\游博网\SourceCode\UBOSI\Web\images\HotelImage\", spiderHotel.HotelPic);
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        updateHotel.HotelPic = fileName;
                    }
                }

                dataContext.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        
        private int GetSnowntownId(string SnowntownName)
        {
            UBOSIEntities dataContext = new UBOSIEntities();
            var query = from snowntown in dataContext.Snowntown
                        where snowntown.SnowntownNameCn == SnowntownName.Replace("酒店","")
                        select snowntown;
            foreach (Snowntown snowtown in query)
            {
                return snowtown.SnowntownId;
            }
            return 0;
        }

        private void InitAllHotel()
        {
            UBOSIEntities dataContext = new UBOSIEntities();
            var query = from city in dataContext.City
                        select city;
           
            foreach (var city in query)
            {
                InitHotelInfo(city.CityId);
            }
            
        }

        private void DownloadImageXml()
        {
            UBOSIEntities dataContext = new UBOSIEntities();
            var query = from hotel in dataContext.Hotel                        
                        select hotel;

            com.ubosi.spider.hotel.HoteInfo.SpiderElongHotelInfo spiderElongHotelInfo = new com.ubosi.spider.hotel.HoteInfo.SpiderElongHotelInfo(null,null);

            int count = 0;
            foreach (var hotel in query)
            {
                spiderElongHotelInfo.GetHotelImage(hotel.HotelId);
                System.Threading.Thread.Sleep(100);
                count++;
            }
            MessageBox.Show("Finish Download " + count.ToString());

        }
        private void button1_Click(object sender, EventArgs e)
        {
            InitAllHotel();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DownloadImageXml();
        }


    }
}
